package info.maxhis.service;

import info.maxhis.entity.Friend;
import info.maxhis.util.CalendarUtil;
import info.maxhis.util.SharedData;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;

public class ListenerService extends Service {
	private Context context;
	private FriendService fs;
	private Handler handler = new Handler();
	private SharedData share;
	
	private Runnable mTask = new Runnable() {
		
		@Override
		public void run() {
			ArrayList<Friend> recentFriends = fs.getRecentFriends();
			if (recentFriends != null && recentFriends.size() > 0) {
				for (Friend f : recentFriends) {
					if (CalendarUtil.daysLeft2Birthday(f) - share.getAdvanceTime() <= 0) {
						share.makeNotification(f);
					}
				}
			}
			
			// 在每一年的1月1号添加所有的生日信息到google calendar
			Calendar now = Calendar.getInstance();
			int month = now.get(Calendar.MONTH);
			int day = now.get(Calendar.DAY_OF_MONTH);
			if (month == 1 && day == 1) {
				ArrayList<Friend> all = fs.getAllFriends();
				if (all != null) {
					for (Friend f : all) {
						fs.addToGoogle(f);
					}
				}
			}
			
			handler.postDelayed(mTask, CalendarUtil.getNextCheckTime());
		}
	};

	@Override
	public void onCreate() {
		context = this;
		share = new SharedData(context);
		fs = new FriendService(context);
		super.onCreate();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		handler.postDelayed(mTask, 2*1000); //开机两秒后开始检查
		super.onStart(intent, startId);
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

}
